#!/bin/sh

### BEGIN INIT INFO
# Provides:             vsm-agent
# Required-Start:       $remote_fs $syslog
# Required-Stop:        $remote_fs $syslog
# Default-Start:        2 3 4 5
# Default-Stop:         0 1 6
# Short-Description:    VSM Storage Agent Service works on Ceph Storage System
### END INIT INFO

PATH=/sbin:/bin:/usr/sbin:/usr/bin

. /lib/lsb/init-functions
if [ -f /etc/init.d/ceph ]; then
    sed -i 's,do_cmd.* 30 $BINDIR.*,do_cmd "timeout 30 $BINDIR/ceph -c $conf --name=osd.$id --keyring=$osd_keyring osd crush create-or-move -- $id ${osd_weight:-${defaultweight:-1}} $osd_location ||:",g' /etc/init.d/ceph;
fi

NAME=vsm-agent
DAEMON=/usr/bin/vsm-agent
CONFIGFILE=/etc/vsm/vsm.conf
PIDFILE=/var/run/vsm/vsm-agent.pid
LOGFILE=/var/log/vsm/vsm-agent.log

test -x $DAEMON || exit 5

LOCKFILE=/var/lock/vsm-agent
if [ ! -d /var/run/vsm ]; then
    mkdir -p /var/run/vsm
    chown -R vsm /var/run/vsm
fi

lock_vsmagent() {
	if [ -x /usr/bin/lockfile-create ]; then
		lockfile-create $LOCKFILE
		lockfile-touch $LOCKFILE &
		LOCKTOUCHPID="$!"
	fi
}

unlock_vsmagent() {
	if [ -x /usr/bin/lockfile-create ] ; then
		kill $LOCKTOUCHPID
		lockfile-remove $LOCKFILE
	fi
}

RUNASUSER=vsm

case $1 in
	start)
		log_daemon_msg "Starting VSM server" "vsm-agent"
		lock_vsmagent
  		start-stop-daemon --start --background --chuid $RUNASUSER --exec $DAEMON -- --config-file=$CONFIGFILE --log-file=$LOGFILE
  		PID=`ps -ef|grep vsm-agent|awk -F ' ' '{ if($3==1) print $2 }'`
  		echo $PID > $PIDFILE

		status=$?
		unlock_vsmagent
		log_end_msg $status
  		;;
	stop)
		log_daemon_msg "Stopping VSM server" "vsm-agent"
  		start-stop-daemon --stop --quiet --oknodo --pidfile $PIDFILE
		log_end_msg $?
		rm -rf $PIDFILE
  		;;
	restart|force-reload)
		$0 stop && sleep 2 && $0 start
  		;;
	try-restart)
		if $0 status >/dev/null; then
			$0 restart
		else
			exit 0
		fi
		;;
	reload)
		exit 3
		;;
	status)
		status_of_proc $DAEMON "VSM server vsm-agent"
		;;
	*)
		echo "Usage: $0 {start|stop|restart|try-restart|force-reload|status}"
		exit 2
		;;
esac
